package com.ysqcould.message.utils.wxmessage;

import com.alibaba.fastjson.JSONObject;
import com.ysqcould.common.core.redis.RedisCache;
import com.ysqcould.common.utils.StringUtils;
import com.ysqcould.common.utils.http.HttpUtils;
import com.ysqcould.common.utils.spring.SpringUtils;

/**
 * 模板消息发送api
 * @author jcd
 */
public class TemplateAPI {
    public static final String ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private static String SENDTEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

    public static JSONObject sendTemplateMsg(Long asId, String templateId, String data, String openid, String url) {
        JSONObject json = new JSONObject();
        if(StringUtils.isBlank(openid)) {
            return json;
        }
        String outJson = "{\"touser\":\""+openid+"\",\"template_id\":\""+templateId+"\",\"url\":\""+url+"\",\"data\":"+data+"}";
        StringBuilder sb = new StringBuilder();
        sb.append("{\"touser\":\"").append(openid).append("\",")
                .append("\"template_id\":\"").append(templateId).append("\",")
                .append("\"url\":\"").append(url).append("\",")
                .append("\"data\":").append(data).append("}")
        ;
        System.out.println("发送模板消息 :" + sb.toString());
        try {
            RedisCache cache=SpringUtils.getBean(RedisCache.class);
            String accessToken = cache.getCacheObject("accessToken" + asId).toString().replace("\"","");
            String requestUrl = SENDTEMPLATE_URL.replace("ACCESS_TOKEN", accessToken);
            String result = HttpUtils.sendPost(requestUrl, sb.toString());
            System.out.println("发送返回结果:" + result);
            json = JSONObject.parseObject(result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return json;
    }


}
